import '../public/index'
import url from '../data/url'
import request from '../data/request'
import {tableConfig, header} from '../data/config'
import store from 'store'

const base = url.base,
  getBuildTypePage = request.getBuildTypePage,
  getBuildingList = request.getBuildingList,
  editBuildingType = request.editBuildingType;

let table,
  storeData

// 初始化表格
table = $('#table').bootstrapTable($.extend({}, tableConfig, {
  url: base + getBuildTypePage,
  queryParams: function (params) {
    return $.extend({
      currentPage: params.pageNumber,
      pageSize: params.pageSize,
    }, $('#searchForm').serializeObject())
  },
  columns: [
    {
      field: 'name',
      title: '楼盘户型',
      valign: 'middle'
    }, {
      field: 'propertyName',
      title: '楼盘名称',
      valign: 'middle'
    }, {
      field: 'type',
      title: '楼盘类型',
      valign: 'middle',
      formatter: (index, row) => {
        switch (index) {
          case 1:
            return '住宅类'
            break;
          case 2:
            return '商务类'
            break;
          case 3:
            return '商业类'
            break;
          case 4:
            return '其他'
            break;
        }
      }
    }, {
      field: 'price',
      title: '预交金额',
      valign: 'middle', formatter: (index, row) => {
        return showNum(row.price)
      }
    }, {
      field: 'equalMoney',
      title: '抵扣金额',
      valign: 'middle', formatter: (index, row) => {
        return showNum(row.equalMoney)
      }
    }, {
      field: 'isShow',
      title: '是否显示',
      valign: 'middle',
      formatter: (index, row) => {
        return index == 0 ? '不显示' : '显示'
      }
    }, {
      field: 'isShow',
      valign: 'middle',
      align: 'center',
      width: '240px',
      title: '操作',
      formatter: (index, row) => {
        return `<div class="btn-group">
                      <button type="button" data-id="${ row.idStr }" class="btn btn-default btn-modify">修改</button>                  
                      <button type="button" data-id="${ row.idStr }" data-status="${ index }" class="btn btn-default btn-isShow">${index == 0 ? '显示' : '不显示'}</button>                  
                      <button type="button" data-id="${ row.idStr }" class="btn btn-default btn-detail">详情</button>                  
                </div>`
      }
    }]
}))

// 点击列表的时候传递数据到全局变量
table.on('click-row.bs.table', (e, data, el) => {
  storeData = data
})

//初始化楼盘名称
getBuild()

function getBuild() {

  $.ajax({
    headers: header,
    type: 'GET',
    url: base + getBuildingList
  })
    .done(function (res) {
      console.log(res)

      let code = res.code,
        project = $('#buildingInfoId');

      if (code == 0) {
        console.log("获取楼盘成功")

        let html = '<option value="">请选择</option>',
          i = 0,
          data = res.object,
          len = data.length;

        for (; i < len; i++) {
          html += `<option value="${ data[i].idStr }">${ data[i].propertyName }</option>`
        }

        project.html(html);
        project.selectize();
      } else {
        project.html('<option value="">请选择</option>')
        layer.msg('获取楼盘失败', {
          icon: 5
        })
      }
    })
    .fail(function (res) {
      console.log(res)
      console.log("error")
      let project = $('#buildingId')
      project.html('<option value="">请选择</option>')

    })
    .always(function (res) {
      console.log("complete")
    })
}

// 搜索
$('#search-btn').on('click', (e) => {
  e.preventDefault();

  table.bootstrapTable('refresh', {
    query: $.extend({
      currentPage: 1,
    }, $('#searchForm').serializeObject())
  })
})

// 是否显示
$(document).on('click', '#table .btn-isShow', (e) => {
  e.preventDefault()

  console.log('开关')

  let id = $(e.target).attr('data-id'),
    status = $(e.target).attr('data-status'),
    isShow = status == 0 ? '1' : '0',
    tit = status == 0 ? '显示' : '不显示',
    data = {
      id: id,
      isShow: isShow
    };

  console.log(JSON.stringify(data))
  bootbox.confirm({
    title: '提示',
    message: `<div>
                <h3 style="margin:.75em 0">改为 ${ tit } ？</h3>
              </div>`,
    buttons: {
      cancel: {
        label: '取消'
      },
      confirm: {
        label: tit
      }
    },
    callback: (result) => {

      if (!result) {
        return
      }

      let loading_modal = layer.msg('提交中...', {
        icon: 16,
        time: 0
      })

      $.ajax({
        headers: header,
        url: base + editBuildingType,
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(data)
      })
        .done(function (res) {
          console.log(res)

          if (res.code == 0) {

            layer.msg('操作成功', {
              icon: 6
            })

            table.bootstrapTable('refresh')

          } else {
            layer.msg('操作失败', {
              icon: 5
            })
          }

        })
        .fail(function (res) {
          console.log(res)

          layer.msg('操作失败', {
            icon: 5
          })

        })
        .always(function (res) {

          console.log("complete")

          layer.close(loading_modal)
        })
    }
  })
})

//跳转至修改页
$(document).on('click', '#table .btn-modify', (e) => {
  e.preventDefault()

  console.log('修改')
  store.set('storeData', storeData)

  let id = $(e.target).attr('data-id')
  window.location.href = `./modify.html?id=${id}`
})

//跳转至详情页
$(document).on('click', '#table .btn-detail', (e) => {
  e.preventDefault()

  console.log('详情')
  store.set('storeData', storeData)

  let id = $(e.target).attr('data-id')
  window.location.href = `./detail.html?id=${id}`
})

//在这里处理storeData里边的equalMoney字段和price字段
function showNum(num) {
  let numStr = (num / 100).toFixed(2)
  // console.log(numStr)
  const pointIndex = numStr.indexOf('.')

  let lastNum = numStr[pointIndex + 1] + numStr[pointIndex + 2]
  // console.log('lastNum===>', lastNum)
  if (lastNum == 0) { //没有角没有分
    return (num / 100).toFixed(0)
  } else if (lastNum[1] == 0 && lastNum[0] > 0) { //有角没有分  100.01
    return (num / 100).toFixed(1)
  } else { //有角有分或者 没有角有分
    return numStr
  }
}